package com.abc.recycling.service.impl;

import com.abc.recycling.domain.Message;
import com.abc.recycling.domain.MessageTemplate;
import com.abc.recycling.mapper.MessageMapper;
import com.abc.recycling.mapper.MessageTemplateMapper;
import com.abc.recycling.service.MessageService;
import com.abc.recycling.service.WebSocketService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {

    private final MessageMapper messageMapper;
    private final WebSocketService webSocketService;
    private final MessageTemplateMapper messageTemplateMapper;
    private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{\\{(.*?)\\}\\}");

    @Override
    @Transactional
    public Message createMessage(Message message) {
        message.setStatus(0);  // 设置为未读
        message.setCreateTime(LocalDateTime.now());
        messageMapper.insert(message);
        
        // 通过WebSocket推送消息
        webSocketService.sendMessageToUser(message.getReceiverId(), message);
        
        return message;
    }

    @Override
    @Transactional
    public void markAsRead(Long messageId) {
        messageMapper.updateStatus(messageId, 1, LocalDateTime.now());
    }

    @Override
    public List<Message> getUserMessages(Long userId) {
        return messageMapper.findByUserId(userId);
    }

    @Override
    public List<Message> getUnreadMessages(Long userId) {
        return messageMapper.findByUserIdAndStatus(userId, 0);
    }

    @Override
    public int getUnreadCount(Long userId) {
        return messageMapper.countUnread(userId);
    }

    @Override
    @Transactional
    public void deleteMessage(Long messageId) {
        messageMapper.deleteById(messageId);
    }

    @Override
    @Transactional
    public void sendOrderStatusNotification(Long userId, String orderNo, String oldStatus, String newStatus) {
        Message message = new Message();
        message.setReceiverId(userId);
        message.setType("ORDER_STATUS");
        message.setTitle("订单状态更新");
        
        String content = String.format("您的订单 %s 状态已从\"%s\"更新为\"%s\"",
                orderNo,
                translateStatus(oldStatus),
                translateStatus(newStatus));
        message.setContent(content);
        
        createMessage(message);
    }

    @Override
    @Transactional
    public void sendSystemNotice(Long userId, String title, String content) {
        Message message = new Message();
        message.setReceiverId(userId);
        message.setType("SYSTEM_NOTICE");
        message.setTitle(title);
        message.setContent(content);
        
        createMessage(message);
    }
    
    @Override
    public List<Message> searchMessages(Long userId, String type, Integer status, String keyword, 
                                      LocalDateTime startTime, LocalDateTime endTime) {
        return messageMapper.search(userId, type, status, keyword, startTime, endTime);
    }
    
    @Override
    @Transactional
    public void deleteMessages(List<Long> messageIds) {
        if (messageIds != null && !messageIds.isEmpty()) {
            messageMapper.deleteByIds(messageIds);
        }
    }
    
    @Override
    @Transactional
    public void markMessagesAsRead(List<Long> messageIds) {
        if (messageIds != null && !messageIds.isEmpty()) {
            messageMapper.markReadByIds(messageIds, LocalDateTime.now());
        }
    }
    
    @Override
    @Transactional
    public void sendMessageWithTemplate(String templateCode, Long userId, Map<String, Object> variables) {
        MessageTemplate template = messageTemplateMapper.findByCode(templateCode);
        if (template == null || template.getStatus() != 1) {
            throw new RuntimeException("消息模板不存在或已禁用");
        }
        
        // 替换标题中的变量
        String title = replaceVariables(template.getTitle(), variables);
        // 替换内容中的变量
        String content = replaceVariables(template.getContent(), variables);
        
        // 创建消息
        Message message = new Message();
        message.setReceiverId(userId);
        message.setType(template.getType());
        message.setTitle(title);
        message.setContent(content);
        
        createMessage(message);
    }
    
    /**
     * 替换模板中的变量
     */
    private String replaceVariables(String template, Map<String, Object> variables) {
        if (template == null || variables == null) {
            return template;
        }
        
        StringBuffer result = new StringBuffer();
        Matcher matcher = VARIABLE_PATTERN.matcher(template);
        
        while (matcher.find()) {
            String variable = matcher.group(1);
            Object value = variables.get(variable);
            matcher.appendReplacement(result, value != null ? value.toString() : "");
        }
        matcher.appendTail(result);
        
        return result.toString();
    }
    
    /**
     * 转换订单状态为中文
     */
    private String translateStatus(String status) {
        if (status == null) {
            return "创建";
        }
        switch (status) {
            case "PENDING":
                return "待接单";
            case "ACCEPTED":
                return "已接单";
            case "PROCESSING":
                return "处理中";
            case "COMPLETED":
                return "已完成";
            case "CANCELLED":
                return "已取消";
            default:
                return status;
        }
    }

    @Override
    public int countUnreadMessages(Long userId) {
        try {
            return messageMapper.countByUserIdAndStatus(userId, 0);  // 0表示未读状态
        } catch (Exception e) {
            // 如果发生异常，返回0，避免影响页面显示
            return 0;
        }
    }

    @Override
    public Message getMessageById(Long messageId) {
        return messageMapper.findById(messageId);
    }

    @Override
    public void sendSystemMessage(String title, String content) {
        Message message = new Message();
        message.setType("SYSTEM");
        message.setTitle(title);
        message.setContent(content);
        message.setCreateTime(LocalDateTime.now());
        message.setStatus(0);  // 未读状态
        messageMapper.insert(message);
    }

    @Override
    public void sendUserMessage(String title, String content, Long userId) {
        Message message = new Message();
        message.setType("USER");
        message.setTitle(title);
        message.setContent(content);
        message.setReceiverId(userId);
        message.setCreateTime(LocalDateTime.now());
        message.setStatus(0);  // 未读状态
        messageMapper.insert(message);
    }
} 